package com.google.code.sharebyblog.bravo.currencyconvertor.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.MessageFormat;

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class GoogleExchangeRateFinder implements ExchangeRateFinder {
	
	//	http://www.google.com/ig/calculator?hl=en&q=100USD=?GBP
	private static final String ENDPOINT = "http://www.google.com/ig/calculator?hl=en&q={0}{1}=?{2}";
	private static final Logger LOGGER = LoggerFactory.getLogger(GoogleExchangeRateFinder.class);

	@Override
	public BigDecimal exchange(String fromCurrency, String toCurrency,BigDecimal amount) throws Exception {
        BigDecimal amountValue = null;
		LOGGER.info("Converting " + fromCurrency + " " + amount.toPlainString() + " into " + toCurrency);
		try {
			String endPoint = MessageFormat.format(ENDPOINT, amount.toPlainString(),fromCurrency,toCurrency);
			JSONObject obj = readJsonFromUrl(endPoint);
			if(obj != null){
				String amountInText = obj.getString("rhs");
				if(amountInText != null){
					String []amountValueInText = amountInText.split(" ");
					String amountValueChar = amountValueInText[0];
					StringBuffer n = new StringBuffer();
					for(int i =0;i < amountValueChar.length() ; i++){
						if(Character.isDigit(amountValueChar.charAt(i)) || amountValueChar.charAt(i) == '.'){
							n.append(amountValueChar.charAt(i));
						}
					}
				
					amountValue = new BigDecimal(n.toString());
				}
				
			}
			
		} catch (IllegalArgumentException e) {
			LOGGER.error("Problems occured while making valid endPoint with parameters." ,e.getMessage());
		}
      
        return amountValue;
	}


	

	private  JSONObject readJsonFromUrl(String url) throws IOException  {
		InputStream is = null;
		JSONObject json = null;
				try {
					is = new URL(url).openStream();
					BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.defaultCharset()));
					String jsonText = readAll(rd);
					json =  (JSONObject) JSONSerializer.toJSON(jsonText);
					
				} catch (IOException e) {
					LOGGER.error(e.getMessage());
					throw e;
				} finally {
					if(is != null){
						try {
							is.close();
						} catch (IOException e) {
							LOGGER.error("Error while closing the stream " + url +" " + e.getMessage());
							throw e;
						}
					}

				}
		return json;
	}
	
	private  String readAll(Reader rd) throws IOException {
		StringBuilder sb = new StringBuilder();
		int cp;
		while ((cp = rd.read()) != -1) {
			sb.append((char) cp);
		}
		return sb.toString();
	}
	

}
